<template>
  <view class="container">
    <!-- 房源图片轮播区 -->
    <view class="house-images">
      <swiper class="swiper" circular autoplay>
        <swiper-item v-for="item in detail.imageList" :key="item">
          <image :src="item" mode="aspectFit" @click="viewImage(item)"></image>
        </swiper-item>
      </swiper>
    </view>
    <!-- 价格信息区 -->
    <view class="price-info">
      <view class="price-item">
        <text class="price">{{ detail.total_count }}人</text>
        <text class="label">总人数</text>
      </view>
      <view class="price-item">
        <text class="price">{{ detail.signed_count }}人</text>
        <text class="label">已报名</text>
      </view>
    </view>
    <!-- 房源标题 -->
    <view class="house-title">
      <text class="title">{{ detail.name }}</text>
      <view class="house-tags">
        <text class="tag" v-for="item in detail.gradList">{{ item }}</text>
      </view>
    </view>
    <!-- 房源详情 -->
    <view class="house-detail">
      <view class="detail-item">
        <text class="label">上课老师</text>
        <text class="value">{{ detail.teacher_name || '-' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">上课时间</text>
        <text class="value">{{ detail.schedule || '-' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">上课地点</text>
        <text class="value">{{ detail.location || '-' }}</text>
      </view>
    </view>
    <!-- 房源描述 -->
    <view class="house-desc">
      <view class="section-title">课程介绍</view>
      <text class="desc-text">
        {{ detail.description }}</text>
    </view>
    <view class="house-desc">
      <view class="section-title">老师介绍</view>
      <u-parse :html="detail.teacher_info"></u-parse>
    </view>
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="sign-btn" @tap="showStudentSelect" :disabled="detail.total_count <= detail.signed_count">
        {{ detail.total_count <= detail.signed_count ? '名额已满' : '立即报名' }}
      </button>
    </view>

    <!-- 学生选择弹窗 -->
    <u-popup v-model="showPopup" mode="bottom" border-radius="24">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择报名学生</text>
          <text class="popup-close" @tap="closeStudentSelect">×</text>
        </view>
        <scroll-view scroll-y class="student-list">
          <view
            v-for="student in studentList"
            :key="student.id"
            class="student-item"
            :class="{ 'student-item-disabled': !isStudentEligible(student) }"
            @tap="selectStudent(student)"
          >
            <image :src="student.avatar || '/static/my/default_avatar.png'" class="student-avatar"></image>
            <view class="student-info">
              <text class="student-name">{{ student.name }}</text>
              <text class="student-detail">{{ formatGrade(student.grade) }}年级{{ student.class_name }}班 - {{ student.student_no }}</text>
            </view>
            <text class="ineligible-text" v-if="!isStudentEligible(student)">年级不符</text>
            <text class="ineligible-text" v-else>点击选择</text>
          </view>
          <view style="height: 5vh" v-if="studentList.length === 0"></view>
          <u-empty style="margin-top: 20px" v-if="studentList.length === 0" text="暂无学生"></u-empty>
          <button class="sign-btn2" @tap="addStudent">
            添加学生
          </button>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      id: '',
      detail: {
        imageList: [],
        gradList: [],
        facilitiesList: []
      },
      studentList: [],
      showPopup: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  onLoad(options) {
    this.id = options.id
  },
  onShow() {
    this.showPopup = false
    // 获取房源详情
    this.getDetail()
  },
  methods: {
    viewImage(image) {
      uni.previewImage({
        current: image,
        urls: this.detail.imageList
      })
    },
    formatGarde(grade) {
      if (!grade) return []
      const grades = {
        '1': '一年级',
        '2': '二年级',
        '3': '三年级',
        '4': '四年级',
        '5': '五年级',
        '6': '六年级',
      }
      const gardeArr = grade.split(',')
      return gardeArr.map(garde => grades[garde])
    },
    getDetail() {
      uni.showLoading()
      return new Promise((resolve) => {
        this.$api.getCourseDetail(this.id).then(res => {
          let imageList = []
          if (res.image) {
            imageList = res.image.split(',')
          }
          let gradList = []
          if (res.grade) {
            gradList = this.formatGarde(res.grade)
          }
          this.detail = {
            ...res,
            imageList: imageList,
            gradList: gradList,
          }
          resolve()
        }).finally(() => {
          uni.hideLoading()
        })
      })
    },
    getStudentList() {
      this.$api.getChildrenList({
        parent_id: this.userInfo.id
      }).then(res => {
        this.studentList = res
      })
    },
    showStudentSelect() {
      if (!this.userInfo || !this.userInfo.id) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
        return
      }
      this.getDetail().then(res => {
        this.showPopup = true
        this.getStudentList()
      })
    },
    closeStudentSelect() {
      this.showPopup = false
    },

    formatGrade(grade) {
      const gradeMap = {
        '1': '一年级',
        '2': '二年级',
        '3': '三年级',
        '4': '四年级',
        '5': '五年级',
        '6': '六年级'
      }
      return gradeMap[grade] || grade
    },
    isStudentEligible(student) {
      if (!this.detail.grade) return false
      const courseGrades = this.detail.grade.split(',')
      return courseGrades.includes(student.grade.toString())
    },
    addStudent() {
      uni.navigateTo({
        url: '/pages/my/children'
      })
    },
    selectStudent(student) {
      if (!this.isStudentEligible(student)) {
        uni.showToast({
          title: '年级不符',
          icon: 'none'
        })
        return
      }
      uni.showModal({
        title: '确认报名',
        content: `确定为${student.name}报名该课程吗？`,
        success: (res) => {
          if (res.confirm) {
            this.$api.createCourseRecord({
              course_id: this.id,
              student_id: student.id,
              parent_id: this.userInfo.id,
              course_name: this.detail.name,
              course_logo: this.detail.logo,
              course_schedule: this.detail.schedule,
              grade: student.grade,
              class_name: student.class_name,
              teacher_name: this.detail.teacher_name,
              location: this.detail.location
            }).then(() => {
              uni.showToast({
                title: '报名成功',
                icon: 'success'
              })
              setTimeout(() => {
                this.closeStudentSelect()
                this.getDetail() // 刷新课程信息
              }, 800)
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
page {
  height: 100%;
  overflow: auto;
  background-color: #f8f8f8;
}
.container {
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  padding-bottom: 100rpx;
}
.house-images {
  position: relative;
  width: 750rpx;
  height: 400rpx;
}
.house-images .swiper {
  width: 100%;
  height: 100%;
}
.house-images image {
  width: 100%;
  height: 100%;
}
.image-count {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  background: rgba(0, 0, 0, 0.6);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
}
.image-count text {
  color: #fff;
  font-size: 24rpx;
  margin-left: 8rpx;
}
.price-info {
  display: flex;
  padding: 30rpx;
  background: #fff;
  margin-bottom: 20rpx;
}
.price-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.price-item .price {
  color: #ff5a5f;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}
.price-item .label {
  color: #999;
  font-size: 24rpx;
}
.house-title {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}
.house-title .title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  line-height: 1.4;
}
.house-tags {
  margin-top: 16rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}
.house-tags .tag {
  padding: 4rpx 16rpx;
  background: #f0f7ff;
  color: #2b85e4;
  border-radius: 4rpx;
  font-size: 24rpx;
}
.house-detail {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-wrap: wrap;
}
.detail-item {
  width: 100%;
  margin-bottom: 20rpx;
}
.detail-item .label {
  color: #999;
  font-size: 26rpx;
  margin-right: 20rpx;
}
.detail-item .value {
  color: #333;
  font-size: 26rpx;
}
.agent-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
.agent-info .avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}
.agent-info .agent-detail {
  flex: 1;
  margin-left: 20rpx;
}
.agent-info .name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}
.agent-info .title {
  font-size: 24rpx;
  color: #666;
}
.contact-buttons {
  display: flex;
  gap: 20rpx;
}
.contact-btn {
  height: 72rpx;
  border-radius: 36rpx;
  background-color: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.house-desc {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}
.section-title {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}
.desc-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}
.location-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}
.location-info .address {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
}
.map-image {
  width: 100%;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}
.distance-info {
  display: flex;
  flex-direction: column;
}
.distance-info text {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);

  .sign-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #3b7ff3;
    color: #fff;
    border-radius: 40rpx;
    font-size: 32rpx;

    &:disabled {
      background: #ccc;
    }
  }
}
.sign-btn2 {
  width: 50%;
  height: 80rpx;
  line-height: 80rpx;
  background: #3b7ff3;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;

  &:disabled {
    background: #ccc;
  }
}

.popup-content {
  background: #fff;
  padding-bottom: env(safe-area-inset-bottom);

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 0 20rpx;
    }
  }

  .student-list {
    min-height: 40vh;
    max-height: 60vh;

    .student-item {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #eee;

      &.student-item-disabled {
        opacity: 0.5;
      }

      .student-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .student-info {
        flex: 1;

        .student-name {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }

        .student-detail {
          font-size: 24rpx;
          color: #666;
          margin-top: 6rpx;
          margin-left: 6rpx;
        }
      }

      .ineligible-text {
        font-size: 24rpx;
        color: #ff4d4f;
      }
    }
  }
}
</style>
